<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据管理 - 备份管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
    <style>
        .backup-container {
            padding: 20px;
        }
        
        .backup-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        
        .backup-tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid #ddd;
            border-bottom: none;
            background: #f5f5f5;
            margin-right: 5px;
        }
        
        .backup-tab.active {
            background: white;
            border-bottom: 1px solid white;
        }
        
        .backup-content {
            display: none;
        }
        
        .backup-content.active {
            display: block;
        }
        
        .backup-actions {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        
        .backup-form {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .backup-list {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .backup-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .backup-item:last-child {
            border-bottom: none;
        }
        
        .backup-info {
            flex: 1;
        }
        
        .backup-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .backup-details {
            color: #666;
            font-size: 14px;
        }
        
        .backup-actions-item {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-warning {
            background: #ffc107;
            color: black;
        }
        
        .btn-info {
            background: #17a2b8;
            color: white;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .status-success {
            color: #28a745;
            font-weight: bold;
        }
        
        .status-failed {
            color: #dc3545;
            font-weight: bold;
        }
        
        .status-processing {
            color: #ffc107;
            font-weight: bold;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        
        .pagination button {
            padding: 8px 12px;
            margin: 0 5px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
        }
        
        .pagination button.active {
            background: #007bff;
            color: white;
        }
        
        
        .log-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            background: white;
        }
        
        .log-item:last-child {
            border-bottom: none;
        }
        
        .log-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .log-operation {
            font-weight: bold;
            color: #007bff;
        }
        
        .log-time {
            color: #666;
            font-size: 14px;
        }
        
        .log-details {
            color: #666;
            font-size: 14px;
        }
        
        .log-level-info {
            color: #17a2b8;
        }
        
        .log-level-warn {
            color: #ffc107;
        }
        
        .log-level-error {
            color: #dc3545;
        }
        
        .log-id {
            background: #f8f9fa;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
            font-weight: bold;
        }
        
        .log-actions {
            display: flex;
            gap: 5px;
        }
    </style>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>
                            <span>数据管理</span>
                        </a>
                    </li>
                    <li>
                        <a href="system.html" class="nav-link">
                            <i class="fas fa-cog"></i>
                            <span>系统设置</span>
                        </a>
                    </li>
                    <!-- <li>
                        <a href="statistics.html" class="nav-link">
                            <i class="fas fa-chart-bar"></i>
                            <span>统计分析</span>
                        </a>
                    </li> -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <div class="backup-container">
                <h2>数据管理</h2>
            
            <div class="backup-tabs">
                <div class="backup-tab active" onclick="switchTab('backup')">备份管理</div>
                <div class="backup-tab" onclick="switchTab('logs')">系统日志</div>
            </div>
            
            <!-- 备份管理页面 -->
            <div id="backup-content" class="backup-content active">
                <div class="backup-actions">
                    <button class="btn btn-primary" onclick="showCreateBackupForm()">创建备份</button>
                    <button class="btn btn-success" onclick="openBackupFolder()">打开备份文件夹</button>
                    <button class="btn btn-info" onclick="refreshBackupList()">刷新列表</button>
                </div>
                
                <div class="backup-form" id="create-backup-form" style="display: none;">
                    <h3>创建备份</h3>
                    <div class="form-group">
                        <label>备份名称:</label>
                        <input type="text" id="backup-name" placeholder="请输入备份名称">
                    </div>
                    <div class="form-group">
                        <label>备份描述:</label>
                        <textarea id="backup-description" rows="3" placeholder="请输入备份描述"></textarea>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-success" onclick="createBackup()">创建备份</button>
                        <button class="btn btn-danger" onclick="hideCreateBackupForm()">取消</button>
                    </div>
                </div>
                
                
                <div class="backup-list" id="backup-list">
                    <!-- 备份列表将在这里动态加载 -->
                </div>
                
                <div class="pagination" id="backup-pagination">
                    <!-- 分页控件将在这里动态加载 -->
                </div>
            </div>
            
            <!-- 系统日志页面 -->
            <div id="logs-content" class="backup-content">
                <div class="backup-actions">
                    <button class="btn btn-info" onclick="refreshLogs()">刷新日志</button>
                    <button class="btn btn-warning" onclick="exportLogs()">导出日志</button>
                    <button class="btn btn-success" onclick="showImportLogsForm()">导入日志</button>
                    <button class="btn btn-danger" onclick="showDeleteLogsDialog()">删除日志</button>
                    <button class="btn btn-secondary" onclick="showClearLogsDialog()">清空日志</button>
                </div>
                
                <!-- 导入日志表单 -->
                <div id="import-logs-form" style="display: none; margin: 20px 0; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;">
                    <h4>导入日志文件</h4>
                    <form id="import-logs-form-element" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="log-file">选择文件:</label>
                            <input type="file" id="log-file" accept=".csv,.txt,.json" required>
                            <small class="form-text text-muted">支持CSV、TXT、JSON格式的日志文件</small>
                        </div>
                        <div class="form-group">
                            <label for="log-format">文件格式:</label>
                            <select id="log-format" class="form-control">
                                <option value="auto">自动检测</option>
                                <option value="csv">CSV格式</option>
                                <option value="txt">TXT格式</option>
                                <option value="json">JSON格式</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success">开始导入</button>
                            <button type="button" class="btn btn-secondary" onclick="hideImportLogsForm()">取消</button>
                        </div>
                    </form>
                </div>
                
                <!-- 删除日志对话框 -->
                <div id="delete-logs-dialog" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center;">
                    <div style="background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); max-width: 600px; width: 90%;">
                        <h3 style="margin-top: 0; color: #333;">删除日志记录</h3>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: bold;">删除方式:</label>
                            <select id="delete-method" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;">
                                <option value="single">删除单条记录</option>
<!--                                <option value="batch">批量删除</option>-->
<!--                                <option value="condition">按条件删除</option>-->
                            </select>
                        </div>
                        
                        <!-- 单条删除 -->
                        <div id="single-delete" style="display: block;">
                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: bold;">日志ID:</label>
                                <input type="number" id="single-log-id" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入要删除的日志ID">
                            </div>
                        </div>
                        
                        <!-- 批量删除 -->
                        <div id="batch-delete" style="display: none;">
                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: bold;">日志ID列表 (用逗号分隔):</label>
                                <textarea id="batch-log-ids" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; height: 100px;" placeholder="请输入要删除的日志ID，用逗号分隔，如：1,2,3,4"></textarea>
                            </div>
                        </div>
                        
                        <!-- 按条件删除 -->
                        <div id="condition-delete" style="display: none;">
                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: bold;">时间范围:</label>
                                <input type="date" id="delete-start-date" style="width: 48%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 4%;">
                                <input type="date" id="delete-end-date" style="width: 48%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                            </div>
                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: bold;">日志级别:</label>
                                <select id="delete-log-level" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                    <option value="">所有级别</option>
                                    <option value="INFO">INFO</option>
                                    <option value="WARN">WARN</option>
                                    <option value="ERROR">ERROR</option>
                                </select>
                            </div>
                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: bold;">模块:</label>
                                <input type="text" id="delete-module" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入模块名称">
                            </div>
                        </div>
                        
                        <div style="text-align: right;">
                            <button onclick="closeDeleteLogsDialog()" style="padding: 8px 16px; margin-right: 10px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 4px; cursor: pointer;">取消</button>
                            <button onclick="executeDeleteLogs()" style="padding: 8px 16px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">删除</button>
                        </div>
                    </div>
                </div>
                
                <!-- 清空日志确认对话框 -->
                <div id="clear-logs-dialog" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center;">
                    <div style="background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); max-width: 400px; width: 90%;">
                        <h3 style="margin-top: 0; color: #dc3545;">⚠️ 清空所有日志</h3>
                        <p style="color: #666; margin-bottom: 20px;">此操作将删除所有日志记录，且无法恢复！</p>
                        <p style="color: #666; margin-bottom: 20px;">请确认是否继续？</p>
                        <div style="text-align: right;">
                            <button onclick="closeClearLogsDialog()" style="padding: 8px 16px; margin-right: 10px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 4px; cursor: pointer;">取消</button>
                            <button onclick="executeClearLogs()" style="padding: 8px 16px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">确认清空</button>
                        </div>
                    </div>
                </div>
                
                <div id="logs-list">
                    <!-- 日志列表将在这里动态加载 -->
                </div>
                
                <div class="pagination" id="logs-pagination">
                    <!-- 分页控件将在这里动态加载 -->
                </div>
            </div>
            
        </main>
    </div>

    <script src="api.js"></script>
    <!-- 移除app.js依赖，避免登录检查冲突 -->
    <script>
        let currentTab = 'backup';
        let currentPage = 1;
        let pageSize = 10;

        // 切换标签页
        function switchTab(tab) {
            // 隐藏所有内容
            document.querySelectorAll('.backup-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签的active类
            document.querySelectorAll('.backup-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的内容
            document.getElementById(tab + '-content').classList.add('active');
            event.target.classList.add('active');
            
            currentTab = tab;
            
            // 根据标签页加载相应数据
            if (tab === 'backup') {
                loadBackupList();
            } else if (tab === 'logs') {
                loadLogs();
            }
        }

        // 显示创建备份表单
        function showCreateBackupForm() {
            document.getElementById('create-backup-form').style.display = 'block';
        }

        // 隐藏创建备份表单
        function hideCreateBackupForm() {
            document.getElementById('create-backup-form').style.display = 'none';
            document.getElementById('backup-name').value = '';
            document.getElementById('backup-description').value = '';
        }

        // 创建备份
        async function createBackup() {
            const backupName = document.getElementById('backup-name').value;
            const description = document.getElementById('backup-description').value;
            
            if (!backupName.trim()) {
                alert('请输入备份名称');
                return;
            }
            
            try {
                const response = await fetch('/api/backup/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        backupName: backupName,
                        description: description
                    })
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert('备份创建成功');
                    hideCreateBackupForm();
                    loadBackupList();
                } else {
                    alert('备份创建失败: ' + result.message);
                }
            } catch (error) {
                console.error('创建备份失败:', error);
                alert('创建备份失败: ' + error.message);
            }
        }

        // 加载备份列表
        async function loadBackupList(page = 1) {
            console.log('开始加载备份列表...');
            try {
                const url = `/api/backup/list?page=${page}&size=${pageSize}`;
                console.log('请求URL:', url);
                
                const response = await fetch(url);
                console.log('响应状态:', response.status);
                
                const result = await response.json();
                console.log('响应数据:', result);
                
                if (result.result === 'SUCCESS') {
                    displayBackupList(result.data.records);
                    displayPagination(result.data, 'backup-pagination', loadBackupList);
                } else {
                    console.error('加载备份列表失败:', result.message);
                    // 显示错误信息给用户
                    const container = document.getElementById('backup-list');
                    container.innerHTML = '<div class="backup-item">加载失败: ' + result.message + '</div>';
                }
            } catch (error) {
                console.error('加载备份列表失败:', error);
                // 显示错误信息给用户
                const container = document.getElementById('backup-list');
                container.innerHTML = '<div class="backup-item">网络错误: ' + error.message + '</div>';
            }
        }

        // 显示备份列表
        function displayBackupList(backups) {
            const container = document.getElementById('backup-list');
            
            if (backups.length === 0) {
                container.innerHTML = '<div class="backup-item">暂无备份记录</div>';
                return;
            }
            
            container.innerHTML = backups.map(backup => `
                <div class="backup-item">
                    <div class="backup-info">
                        <div class="backup-name">${backup.backupName}</div>
                        <div class="backup-details">
                            编码: ${backup.backupCode} | 
                            大小: ${formatFileSize(backup.backupSize)} | 
                            时间: ${formatDateTime(backup.backupTime)} | 
                            状态: <span class="status-${backup.backupStatus}">${getStatusText(backup.backupStatus)}</span>
                        </div>
                        <div class="backup-details">描述: ${backup.description || '无'}</div>
                    </div>
                    <div class="backup-actions-item">
                        <button class="btn btn-danger" onclick="deleteBackup(${backup.backupId})">删除</button>
                    </div>
                </div>
            `).join('');
        }


        // 删除备份
        async function deleteBackup(backupId) {
            if (!confirm('确定要删除此备份吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/backup/delete/${backupId}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert('备份删除成功');
                    loadBackupList();
                } else {
                    alert('备份删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除备份失败:', error);
                alert('删除备份失败: ' + error.message);
            }
        }



        // 刷新备份列表
        function refreshBackupList() {
            loadBackupList();
        }

        // 打开备份文件夹
        async function openBackupFolder() {
            const backupPath = 'D:\\tushuguanli\\backups';
            
            try {
                const response = await fetch('/api/backup/open-folder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        path: backupPath
                    })
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert('备份文件夹已打开！');
                } else {
                    alert(`无法自动打开文件夹，请手动打开：\n${backupPath}`);
                }
            } catch (error) {
                console.error('打开文件夹失败:', error);
                alert(`无法自动打开文件夹，请手动打开：\n${backupPath}`);
            }
        }

        // 加载系统日志
        async function loadLogs(page = 1) {
            try {
                const response = await fetch(`/api/backup/logs?page=${page}&size=${pageSize}`);
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    displayLogs(result.data.records);
                    displayPagination(result.data, 'logs-pagination', loadLogs);
                } else {
                    console.error('加载系统日志失败:', result.message);
                }
            } catch (error) {
                console.error('加载系统日志失败:', error);
            }
        }

        // 显示系统日志
        function displayLogs(logs) {
            const container = document.getElementById('logs-list');
            
            if (logs.length === 0) {
                container.innerHTML = '<div class="log-item">暂无日志记录</div>';
                return;
            }
            
            container.innerHTML = logs.map(log => `
                <div class="log-item">
                    <div class="log-header">
                        <div class="log-operation">${log.operation}</div>
                        <div class="log-time">${formatDateTime(log.operationTime)}</div>
                        <div class="log-id" style="margin-left: 10px;">ID: ${log.logId}</div>
                        <div class="log-actions" style="margin-left: auto;">
                            <button onclick="quickDeleteLog(${log.logId})" style="background: #dc3545; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 12px; cursor: pointer;">删除</button>
                        </div>
                    </div>
                    <div class="log-details">
                        用户: ${log.userName || '系统'} | 
                        IP: ${log.ipAddress} | 
                        级别: <span class="log-level-${log.logLevel?.toLowerCase()}">${log.logLevel}</span> | 
                        模块: ${log.module}
                    </div>
                    <div class="log-details">备注: ${log.remark || '无'}</div>
                </div>
            `).join('');
        }


        // 刷新日志
        function refreshLogs() {
            loadLogs();
        }

        // 导出日志
        function exportLogs() {
            showExportDialog();
        }

        // 显示导出对话框
        function showExportDialog() {
            // 创建对话框HTML
            const dialogHtml = `
                <div id="export-dialog" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; justify-content: center; align-items: center;">
                    <div style="background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); max-width: 500px; width: 90%;">
                        <h3 style="margin-top: 0; color: #333;">导出系统日志</h3>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: bold;">导出格式:</label>
                            <select id="export-format" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                <option value="csv">CSV (Excel兼容)</option>
                                <option value="txt">TXT (纯文本)</option>
                                <option value="json">JSON (结构化数据)</option>
                            </select>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: bold;">时间范围:</label>
                            <select id="time-range" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;">
                                <option value="">全部时间</option>
                                <option value="today">今天</option>
                                <option value="yesterday">昨天</option>
                                <option value="week">最近7天</option>
                                <option value="month">最近30天</option>
                                <option value="custom">自定义</option>
                            </select>
                            <div id="custom-date" style="display: none;">
                                <input type="date" id="start-date" style="width: 48%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 4%;">
                                <input type="date" id="end-date" style="width: 48%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                            </div>
                        </div>
                        
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: bold;">日志级别:</label>
                            <select id="log-level" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                <option value="">所有级别</option>
                                <option value="INFO">INFO (信息)</option>
                                <option value="WARN">WARN (警告)</option>
                                <option value="ERROR">ERROR (错误)</option>
                            </select>
                        </div>
                        
                        <div style="text-align: right;">
                            <button onclick="closeExportDialog()" style="padding: 8px 16px; margin-right: 10px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 4px; cursor: pointer;">取消</button>
                            <button onclick="executeExport()" style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">导出</button>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加到页面
            document.body.insertAdjacentHTML('beforeend', dialogHtml);
            
            // 绑定时间范围选择事件
            document.getElementById('time-range').addEventListener('change', function() {
                const customDate = document.getElementById('custom-date');
                if (this.value === 'custom') {
                    customDate.style.display = 'block';
                } else {
                    customDate.style.display = 'none';
                }
            });
        }

        // 关闭导出对话框
        function closeExportDialog() {
            const dialog = document.getElementById('export-dialog');
            if (dialog) {
                dialog.remove();
            }
        }

        // 执行导出
        function executeExport() {
            const format = document.getElementById('export-format').value;
            const timeRange = document.getElementById('time-range').value;
            const logLevel = document.getElementById('log-level').value;
            
            let url = `/api/backup/export-logs?format=${format}`;
            
            // 处理时间范围
            if (timeRange && timeRange !== '') {
                if (timeRange === 'custom') {
                    const startDate = document.getElementById('start-date').value;
                    const endDate = document.getElementById('end-date').value;
                    if (startDate) url += `&startDate=${startDate}`;
                    if (endDate) url += `&endDate=${endDate}`;
                } else {
                    const dates = getDateRange(timeRange);
                    if (dates.start) url += `&startDate=${dates.start}`;
                    if (dates.end) url += `&endDate=${dates.end}`;
                }
            }
            
            // 处理日志级别
            if (logLevel) {
                url += `&logLevel=${logLevel}`;
            }
            
            // 创建隐藏的链接来触发下载
            const link = document.createElement('a');
            link.href = url;
            link.download = `system_logs_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.${format}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 关闭对话框
            closeExportDialog();
            
            alert('日志导出已开始，请检查浏览器下载文件夹');
        }

        // 获取日期范围
        function getDateRange(range) {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            
            const formatDate = (date) => {
                return date.toISOString().split('T')[0];
            };
            
            switch (range) {
                case 'today':
                    return { start: formatDate(today), end: formatDate(today) };
                case 'yesterday':
                    return { start: formatDate(yesterday), end: formatDate(yesterday) };
                case 'week':
                    const weekAgo = new Date(today);
                    weekAgo.setDate(weekAgo.getDate() - 7);
                    return { start: formatDate(weekAgo), end: formatDate(today) };
                case 'month':
                    const monthAgo = new Date(today);
                    monthAgo.setDate(monthAgo.getDate() - 30);
                    return { start: formatDate(monthAgo), end: formatDate(today) };
                default:
                    return { start: null, end: null };
            }
        }

        // 显示导入日志表单
        function showImportLogsForm() {
            document.getElementById('import-logs-form').style.display = 'block';
        }

        // 隐藏导入日志表单
        function hideImportLogsForm() {
            document.getElementById('import-logs-form').style.display = 'none';
            document.getElementById('import-logs-form-element').reset();
        }

        // 处理日志导入
        document.getElementById('import-logs-form-element').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const fileInput = document.getElementById('log-file');
            const formatSelect = document.getElementById('log-format');
            
            if (!fileInput.files[0]) {
                alert('请选择要导入的文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            formData.append('format', formatSelect.value);
            
            try {
                const response = await fetch('/api/backup/import-logs', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    const data = result.data;
                    let message = `导入完成！\n\n`;
                    message += `文件名: ${data.fileName}\n`;
                    message += `格式: ${data.format}\n`;
                    message += `总记录数: ${data.totalCount}\n`;
                    message += `成功: ${data.successCount}\n`;
                    message += `失败: ${data.errorCount}\n`;
                    
                    if (data.errors && data.errors.length > 0) {
                        message += `\n错误详情:\n${data.errors.slice(0, 5).join('\n')}`;
                        if (data.errors.length > 5) {
                            message += `\n... 还有 ${data.errors.length - 5} 个错误`;
                        }
                    }
                    
                    alert(message);
                    
                    // 隐藏表单并刷新日志列表
                    hideImportLogsForm();
                    loadLogs();
                } else {
                    alert('导入失败: ' + result.message);
                }
            } catch (error) {
                console.error('导入日志失败:', error);
                alert('导入失败: ' + error.message);
            }
        });

        // 显示删除日志对话框
        function showDeleteLogsDialog() {
            document.getElementById('delete-logs-dialog').style.display = 'flex';
        }

        // 关闭删除日志对话框
        function closeDeleteLogsDialog() {
            document.getElementById('delete-logs-dialog').style.display = 'none';
            // 重置表单
            document.getElementById('delete-method').value = 'single';
            document.getElementById('single-log-id').value = '';
            document.getElementById('batch-log-ids').value = '';
            document.getElementById('delete-start-date').value = '';
            document.getElementById('delete-end-date').value = '';
            document.getElementById('delete-log-level').value = '';
            document.getElementById('delete-module').value = '';
            updateDeleteMethod();
        }

        // 显示清空日志对话框
        function showClearLogsDialog() {
            document.getElementById('clear-logs-dialog').style.display = 'flex';
        }

        // 关闭清空日志对话框
        function closeClearLogsDialog() {
            document.getElementById('clear-logs-dialog').style.display = 'none';
        }

        // 更新删除方式显示
        function updateDeleteMethod() {
            const method = document.getElementById('delete-method').value;
            document.getElementById('single-delete').style.display = method === 'single' ? 'block' : 'none';
            document.getElementById('batch-delete').style.display = method === 'batch' ? 'block' : 'none';
            document.getElementById('condition-delete').style.display = method === 'condition' ? 'block' : 'none';
        }

        // 执行删除日志
        async function executeDeleteLogs() {
            const method = document.getElementById('delete-method').value;
            
            try {
                let response;
                
                if (method === 'single') {
                    const logId = document.getElementById('single-log-id').value;
                    if (!logId) {
                        alert('请输入要删除的日志ID');
                        return;
                    }
                    
                    response = await fetch(`/api/backup/delete-log/${logId}`, {
                        method: 'DELETE'
                    });
                    
                } else if (method === 'batch') {
                    const logIdsText = document.getElementById('batch-log-ids').value;
                    if (!logIdsText.trim()) {
                        alert('请输入要删除的日志ID列表');
                        return;
                    }
                    
                    const logIds = logIdsText.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
                    if (logIds.length === 0) {
                        alert('请输入有效的日志ID');
                        return;
                    }
                    
                    response = await fetch('/api/backup/batch-delete-logs', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ logIds: logIds })
                    });
                    
                } else if (method === 'condition') {
                    const startDate = document.getElementById('delete-start-date').value;
                    const endDate = document.getElementById('delete-end-date').value;
                    const logLevel = document.getElementById('delete-log-level').value;
                    const module = document.getElementById('delete-module').value;
                    
                    response = await fetch('/api/backup/delete-logs-by-condition', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            startDate: startDate || null,
                            endDate: endDate || null,
                            logLevel: logLevel || null,
                            module: module || null
                        })
                    });
                }
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert(result.data.message || result.data);
                    closeDeleteLogsDialog();
                    loadLogs();
                } else {
                    alert('删除失败: ' + result.message);
                }
                
            } catch (error) {
                console.error('删除日志失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 执行清空日志
        async function executeClearLogs() {
            try {
                const response = await fetch('/api/backup/clear-all-logs', {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert(result.data);
                    closeClearLogsDialog();
                    loadLogs();
                } else {
                    alert('清空失败: ' + result.message);
                }
                
            } catch (error) {
                console.error('清空日志失败:', error);
                alert('清空失败: ' + error.message);
            }
        }

        // 快速删除日志
        async function quickDeleteLog(logId) {
            if (!confirm(`确定要删除日志ID为 ${logId} 的记录吗？`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/backup/delete-log/${logId}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.result === 'SUCCESS') {
                    alert('删除成功');
                    loadLogs();
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除日志失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 绑定删除方式选择事件
        document.addEventListener('DOMContentLoaded', function() {
            const deleteMethodSelect = document.getElementById('delete-method');
            if (deleteMethodSelect) {
                deleteMethodSelect.addEventListener('change', updateDeleteMethod);
            }
        });


        // 显示分页控件
        function displayPagination(pageData, containerId, loadFunction) {
            const container = document.getElementById(containerId);
            const totalPages = pageData.pages;
            const currentPage = pageData.current;
            
            let html = '';
            
            // 上一页
            if (currentPage > 1) {
                html += `<button onclick="${loadFunction.name}(${currentPage - 1})">上一页</button>`;
            }
            
            // 页码
            for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
                html += `<button class="${i === currentPage ? 'active' : ''}" onclick="${loadFunction.name}(${i})">${i}</button>`;
            }
            
            // 下一页
            if (currentPage < totalPages) {
                html += `<button onclick="${loadFunction.name}(${currentPage + 1})">下一页</button>`;
            }
            
            container.innerHTML = html;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN');
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'success': '成功',
                'failed': '失败',
                'processing': '处理中',
                'unpaid': '未支付',
                'paid': '已支付',
                'refunded': '已退款'
            };
            return statusMap[status] || status;
        }

        // 导航栏相关函数
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        function showProfile() {
            alert('个人资料功能待实现');
        }

        function changePassword() {
            alert('修改密码功能待实现');
        }

        function logout() {
            if (confirm('确定要退出登录吗？')) {
                window.location.href = 'login.html';
            }
        }

        // 获取当前用户信息
        function getCurrentUser() {
            try {
                const userStr = localStorage.getItem('currentUser');
                if (userStr) {
                    return JSON.parse(userStr);
                } else {
                    // 如果没有用户信息，创建一个默认的管理员用户
                    const defaultUser = {
                        userId: 1,
                        username: 'admin',
                        realName: '系统管理员',
                        role: 'system_admin'
                    };
                    localStorage.setItem('currentUser', JSON.stringify(defaultUser));
                    return defaultUser;
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                // 返回默认用户
                return {
                    userId: 1,
                    username: 'admin',
                    realName: '系统管理员',
                    role: 'system_admin'
                };
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu && authManager) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，开始初始化...');
            
            // 检查页面访问权限
            if (!PermissionControl.checkPageAccess()) {
                return;
            }
            
            // 获取当前用户信息
            const currentUser = authManager.getCurrentUser();
            if (!currentUser) {
                Utils.showMessage('用户信息获取失败，请重新登录', 'error');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
                return;
            }
            
            // 生成侧边栏菜单
            generateSidebarMenu();
            
            // 测试基本功能
            console.log('测试侧边栏切换功能...');
            const sidebar = document.getElementById('sidebar');
            if (sidebar) {
                console.log('侧边栏元素找到:', sidebar);
            } else {
                console.error('侧边栏元素未找到!');
            }
            
            // 初始化用户信息
            if (currentUser) {
                document.getElementById('currentUserName').textContent = currentUser.realName || '管理员';
                console.log('用户信息已设置:', currentUser.realName);
            } else {
                console.log('未找到用户信息，使用默认值');
            }
            
            // 加载备份列表
            loadBackupList();
        });
    </script>
</body>
</html>
